<?php


namespace App\Model\Logic;


use App\Exception\HttpExecption;
use App\Model\Dao\ManagerDao;
use App\Model\Entity\Manager;
use App\Validator\LoginValidator;
use App\Validator\User\UserNameValidator;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Http\Session\HttpSession;

/**
 * 管理员登录
 * @Bean()
 * @package App\Model\Logic
 */
class LoginLogic
{
    /**
     * @Inject()
     * @var ManagerDao
     */
    private $managerdao;

    /**
     * 登录验证
     * @param $data
     * @throws HttpExecption
     * @throws \Swoft\Db\Exception\DbException
     * @throws \Swoft\Validator\Exception\ValidatorException
     */
    public function checkLogin($data)
    {
        //验证请求数据
        // validate($data,"LoginValidator",[],[UserNameValidator::class]);
        validate($data,"LoginValidator",[],["NameValidator"]);
        //和数据中的用户进行对比
        $user = $this->managerdao->getUserFromUsername($data['username']);
        if(!$user){
            throw new HttpExecption("用户不存在",1);
        }
        if(password_verify($data['password'],$user['password'])){
            //记录用户登录状态
            HttpSession::current()->set("userid",$user['id']);
            HttpSession::current()->set("username",$user['username']);
            throw new HttpExecption("登录成功",0);
        }
        throw new HttpExecption("密码不正确",1);
    }

    /**
     * 判断用户登录状态
     */
    public function checkLoginStatus(){
        if(HttpSession::current()->has("username") && HttpSession::current()->has("userid")){
           return true;
        }
        return false;
    }
}
